package com.sskj.jd.service.impl;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import javax.transaction.Transactional;

import org.apache.commons.lang.StringUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.CrossOrigin;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.sskj.common.vo.SuccessResponse;
import com.sskj.core.exception.MException;
import com.sskj.dingtalk.exception.OApiException;
import com.sskj.dingtalk.service.impl.DingTalkMessageServiceImpl;
import com.sskj.dingtalk.utils.CalendarUtil;
import com.sskj.dingtalk.utils.CodingUtil;
import com.sskj.dingtalk.utils.HttpHelper;
import com.sskj.dingtalk.vo.TiXingRenWuNeiRongVO;
import com.sskj.jd.domain.entity.FoundWT;
import com.sskj.jd.domain.entity.JianDuJiLuCJJG;
import com.sskj.jd.domain.entity.JianDuJiLuRenYuan;
import com.sskj.jd.domain.entity.WenTiFILE;
import com.sskj.jd.domain.entity.WenTiIMG;
import com.sskj.jd.domain.entity.WenTiLX;
import com.sskj.jd.domain.entity.ZhiLiangJBTGTZS;
import com.sskj.jd.repository.EmployeeForRepository;
import com.sskj.jd.repository.ZhiLiangJBTGTZSRepository;
import com.sskj.jd.trans.ZhiLiangJBTGTZSTrans;
import com.sskj.jd.vo.ZhiLiangJBTGTZSVO;
import com.sskj.personnel.domain.entity.EmployeeEntity;
import com.sskj.personnel.repository.EmployeeRepository;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;

@RestController
@RequestMapping(value = "/jd/zljbtgtzs", method = { RequestMethod.POST, RequestMethod.GET })
@Transactional
@Api(value = "质量局部停工通知书", description = "质量局部停工通知书")
public class ZhiLiangJBTGTZSServiceImpl {

	protected final Log logger = LogFactory.getLog(ZhiLiangJBTGTZSServiceImpl.class);

	@Value("${sskj.conf.restUrl}")
	private String restUrl;

	@Autowired
	ZhiLiangJBTGTZSRepository zhiLiangJBTGTZSRepostiory;

	@Autowired
	EmployeeRepository employeeRepository;
	
	@Autowired
	EmployeeForRepository employeeForRepository;		

	@Autowired
	DingTalkMessageServiceImpl dingTalkMessageServiceImpl;

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/save", method = { RequestMethod.POST })
	@ApiOperation(value = "新增质量局部停工通知书", notes = "新增质量局部停工通知书", httpMethod = "POST")
	public SuccessResponse save(@RequestBody ZhiLiangJBTGTZS zhiLiangJBTGTZS) throws Exception {

		ZhiLiangJBTGTZS oldZhiLiangJBTGTZS = null;

		if (zhiLiangJBTGTZS.getId() != null) {
			oldZhiLiangJBTGTZS = zhiLiangJBTGTZSRepostiory.get(zhiLiangJBTGTZS.getId());
		}

		if (oldZhiLiangJBTGTZS == null) {
			String cdlike = "宜市建监ZLTG【" + CalendarUtil.getYearyyyy(Calendar.getInstance()) + "%】";
			String maxCode = zhiLiangJBTGTZSRepostiory.maxCode(cdlike, 30);
			String coding = CodingUtil.getMaxIDQuery(maxCode, cdlike, 18);
			zhiLiangJBTGTZS.setCoding(coding);
			zhiLiangJBTGTZS.getEng().setOid(zhiLiangJBTGTZS.getEng().getId());
			zhiLiangJBTGTZS.getEng().setId(null);

		}

		for (JianDuJiLuRenYuan jdry : zhiLiangJBTGTZS.getJdrys()) {
			EmployeeEntity emp = employeeRepository.findByDD_Id(jdry.getEmplId());
			if (emp != null) {
				jdry.setUserId(emp.getResteasy_emp_id());
			}
			else
			{
				EmployeeEntity emp2 = employeeForRepository.findByName(jdry.getName());
				if (emp2 != null) {
					jdry.setEmplId(emp2.getDdId());
					jdry.setName(emp2.getName());					
					jdry.setUserId(emp2.getResteasy_emp_id());
				}				 
			}
			jdry.setJdjl(zhiLiangJBTGTZS);
			jdry.setCreatorId(zhiLiangJBTGTZS.getCreatorId());

		}

		for (JianDuJiLuCJJG cjjg : zhiLiangJBTGTZS.getCjjgs()) {
			cjjg.setJdjl(zhiLiangJBTGTZS);
			cjjg.setCreatorId(zhiLiangJBTGTZS.getCreatorId());

		}

		for (FoundWT wt : zhiLiangJBTGTZS.getWt()) {
			wt.setJdjl(zhiLiangJBTGTZS);
			for (WenTiFILE file : wt.getFiles()) {
				file.setWt(wt);
				file.setCreatorId(zhiLiangJBTGTZS.getCreatorId());
			}

			for (WenTiIMG img : wt.getImages()) {
				img.setWt(wt);
				img.setCreatorId(zhiLiangJBTGTZS.getCreatorId());
			}

			for (WenTiLX lx : wt.getWtlx()) {
				lx.setWt(wt);
				lx.setCreatorId(zhiLiangJBTGTZS.getCreatorId());
			}
		}
		zhiLiangJBTGTZSRepostiory.save(zhiLiangJBTGTZS);
		return SuccessResponse.newInstance();
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/upload", method = { RequestMethod.POST })
	@ApiOperation(value = "上传质量局部停工通知书", notes = "上传质量局部停工通知书", httpMethod = "POST")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "质量局部停工通知书 IDS", paramType = "form", required = true, dataType = "string") })
	public void upload(String id) throws MException {
		ZhiLiangJBTGTZS oldZhiLiangJBTGTZS = zhiLiangJBTGTZSRepostiory.get(id);
		try {

			oldZhiLiangJBTGTZS.setIsUpload(true);
			TiXingRenWuNeiRongVO tx = upload(oldZhiLiangJBTGTZS);
			dingTalkMessageServiceImpl.sendOAMessage(dingTalkMessageServiceImpl.reNextShenHeMessage(tx));

		} catch (OApiException e) {
			e.printStackTrace();
			if (e.getErrCode() == 2) {
				throw new MException("request_timeout");
			} else {
				throw new MException("system_error");
			}
		} catch (MException e) {
			throw e;
		}
		zhiLiangJBTGTZSRepostiory.save(oldZhiLiangJBTGTZS);
	}

	// 同步往监督系统
	public TiXingRenWuNeiRongVO upload(ZhiLiangJBTGTZS zhiLiangJBTGTZS) throws OApiException {

		ZhiLiangJBTGTZSTrans trans = new ZhiLiangJBTGTZSTrans(zhiLiangJBTGTZS);
		ZhiLiangJBTGTZSVO vo = trans.returnVO();
		EmployeeEntity emp = employeeRepository.findByDD_Id(zhiLiangJBTGTZS.getCreatorId());
		if (emp != null) {
			vo.setCreateId(emp.getResteasy_emp_id());
		}
		JSONObject obj = HttpHelper.httpPost(restUrl + "dingtalk/jd/zljbtgtzs/up", vo);
		if (null == obj) {
			throw new OApiException(1, "");
		} else {
			return JSON.parseObject(obj.getString("result"), TiXingRenWuNeiRongVO.class);
		}
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/get", method = { RequestMethod.POST })
	@ApiImplicitParams({ @ApiImplicitParam(name = "spId", value = "记录ID", paramType = "form", dataType = "string") })
	@ApiOperation(value = "获取质量局部停工通知书", notes = "获取质量局部停工通知书", httpMethod = "GET")
	public ZhiLiangJBTGTZS get(String spId) throws Exception {

		ZhiLiangJBTGTZS ZhiLiangJBTGTZS = zhiLiangJBTGTZSRepostiory.findOneById(spId);
		return ZhiLiangJBTGTZS;
	}

	@CrossOrigin(origins = "*", maxAge = 3600)
	@RequestMapping(value = "/del", method = { RequestMethod.POST, RequestMethod.DELETE })
	@ApiOperation(value = "删除质量局部停工通知书", notes = "删除质量局部停工通知书  多个质量局部停工通知书ID用,号分隔", httpMethod = "DELETE")
	@ApiImplicitParams({
			@ApiImplicitParam(name = "id", value = "质量局部停工通知书 IDS", paramType = "form", required = true, dataType = "string") })
	public void del(String id) {
		if (StringUtils.isNotEmpty(id)) {
			String[] idsArr = id.split(",");
			List<String> list = new ArrayList<String>();

			if (idsArr != null) {
				for (String idd : idsArr) {
					if (!idd.equals("ADMIN")) {
						list.add(idd);
					}
				}
				zhiLiangJBTGTZSRepostiory.delete(list);
			}
		}

	}

}
